class Main extends egret.DisplayObjectContainer {

		private _myLoader:GYLite.GYLoader;
		private _resCount:number=0;
		private _resMax:number=0;
		private _soundArr:Array<string>;
		public mainUI:GYLite.GYSprite;
		public static instance:Main;
		private _dragLock:boolean;
		private _preloadVec:UICtrlData[]=[];
		private _resName:string;
		private _loadCount:number=0;
		private _root:string;
		private _configRoot:string;
		private _version:string; 
    	public constructor()
		{
			super();				
			Log.init(); 
			Log.writeLog(MultiLang.str11 + "_" + GameManager.version + "_" + (window["release"]?"":"debug:true") + "-" + location.href + "\n" + Browser.userAgent + ",GPU:"+Browser.getGPUInfo(), Log.WARN);			
			Browser.browswerInit();
			var s = this;
			GameManager.game = s;
			s._myLoader = GYLite.GYLoader.getDefaultLoader();
			if(s.stage)
				s.projInit();
			else
				s.addEventListener(egret.Event.ADDED_TO_STAGE, s.addToStage,s);	
			if(egret.wxgame.debug)
			debugger;
		}
		private addToStage(e:egret.Event):void
		{	
			this.projInit();
		}
		private projInit():void
		{
			if(!Browser.onMobile)
				this.dragLock(true);			
			var s = this;
			Main.instance = s;					
			if(egret.wxgame.wx)
				egret.wxgame.wx.setEnableDebug({enableDebug:true});
			Log.writeLog("屏幕宽高:w-" + s.stage.stageWidth + ",h-" + s.stage.stageHeight, Log.WARN);
			
			s.removeEventListener(egret.Event.ADDED_TO_STAGE, s.addToStage, s);
			
			let globalObj:any;
			globalObj = window;
			s._root = globalObj.proj_root?globalObj.proj_root:URLConf.DEFAULT_ROOT;
			s._configRoot = globalObj.proj_configRoot?globalObj.proj_configRoot:s._root;
			s._version = globalObj.game_version?globalObj.game_version:"";
			GYLite.GYSprite.Init(s.stage, new Win7SkinTheme, null);
			ProtoExt.inject();													
			GameManager.getInstance().engineInited();						
			if(Net.getInstance().check(s.loadCfg,s,null,1))
				s.loadCfg();
		}
		public loadCfg():void
		{
			let s = this;
			Log.writeLog(MultiLang.str8, Log.IMPORTANT);
			
			let ver:string;            			
			ver = URLConf.getCfgVer("");
			GameManager.getInstance().loadData(s._configRoot+"configs/"+UserData.getInstance().getPlatform()+"_config.json" + (ver.length > 0?"?" + ver:""), s.configLoaded,s,null,GYLite.GYLoader.TYPE_JSON,HTTPConf.M_GET,null,false);	
		}
		public get myLoader():GYLite.GYLoader
		{var s = this;
			return s._myLoader;
		}
		private configLoaded(loadInfo:GYLite.LoadInfo):void
		{let s = this;
			if(loadInfo.content == null)
			{				
				Net.getInstance().netSendAgain(1);
				return;
			}
			Net.getInstance().netComplete(1);
			let cfg:any;			
			cfg = loadInfo.content.res;			
			GameManager.getInstance().setConfig(cfg);			
			if(cfg.res!=null)
				s._resName = cfg.res;
			else
				s._resName = UserData.getInstance().getPlatform() + "_res";			
			let ver:string;
			ver = URLConf.getCfgVer("");
			GameManager.getInstance().loadData(s._root + s._resName + (ver.length > 0?"?" + ver:""),s.resLoadComp,s,s.resProg,GYLite.GYLoader.TYPE_BINARY,HTTPConf.M_GET,null,{save:false},UIControl.FAIL_RELOAD_COUNT);
			Log.loadLog(loadInfo);			
		}
		private resProg(e:egret.Event):void{
			let l:GYLite.SeqURLLoader = e.currentTarget;						
			GameManager.getInstance().globalLoad.globalLoadPercent(l.progressData.loaded, l.progressData.total, "加载主程序资源");
		}       
		private resLoadComp(loadInfo:GYLite.LoadInfo):void
		{var s = this;			
			if(loadInfo.content == null)
			{
				++s._loadCount;
				if(s._loadCount == 3)
				{
					s._loadCount = 0;	
					Log.writeLog(MultiLang.str62 + "," + s._resName + "!" + loadInfo.msg,Log.WARN);
					return;
				}							
				GYLite.TimeManager.timeOut(function():void{		
					let ver:string;
					ver = URLConf.getResVer("");							
					GameManager.getInstance().loadData(s._root + s._resName + (ver.length > 0?"?" + ver:"") + Math.random(),s.resLoadComp,s,null,GYLite.GYLoader.TYPE_BINARY,HTTPConf.M_GET,null,{save:false});
				},s,1000);				
				Log.writeLog(MultiLang.str60 + loadInfo.msg,Log.WARN);
				// s.initUI();
				return;
			}			
			s._loadCount = 0;
			let l:GYLite.CompressLoadInfo = s._myLoader.loadGYCompressBytes(loadInfo.content.res,s.resUncompressComp,s,null,s.resUncompressPorg);			
			Log.writeLog(MultiLang.str66 + "-length:" + l.progressInfo[0].length + "-version:"+l.progressInfo[0].version+"-size:"+l.progressInfo[0].size,Log.VERBOSE);
		}	
		private resUncompressPorg(l:GYLite.CompressLoadInfo):void
		{
			// GYLite.LoadUI.getInstance().setProg(l.resMax - l.resCount, l.resMax, "解压中...");
			// Log.writeLog(MultiLang.str66 + (l.resMax - l.resCount) + "/" + l.resMax + "-" + l.progressInfo[l.progressInfo.length - 1].key,Log.VERBOSE);
		}
		private resUncompressComp(l:GYLite.CompressLoadInfo):void
		{let s = this;
			// GYLite.LoadUI.getInstance().setProg(l.resMax - l.resCount, l.resMax, "解压中...");
			if(l.errorCode > 0)
			{			
				++s._loadCount;
				if(s._loadCount == 3)
				{
					s._loadCount = 0;
					Log.writeLog(MultiLang.str62 + "," + s._resName + "!" + l.msg,Log.WARN);
					return;
				}			
				Log.writeLog(MultiLang.str60 + l.msg,Log.WARN);
				GYLite.TimeManager.timeOut(function():void{									
					GameManager.getInstance().loadData(s._root + s._resName + URLConf.getResVer() + Math.random(),s.resLoadComp,s,null,GYLite.GYLoader.TYPE_BINARY,HTTPConf.M_GET,null,{save:false});
				},s,2000);
				return;
			}			
			if(l.resCount == 0)
			{
				Log.uncompressLog(l, s._resName);
        		Log.writeLog(MultiLang.str10, Log.IMPORTANT);						
				s.initUI();
			}
		}
		private initUI():void
		{var s = this;			
			URLConf.resetRoot();
			GYLite.GYSprite.skinTheme = new Win7SkinTheme;			
			GameManager.getInstance().gameInit();				
			if(UserData.getInstance().isRelease != ProjType.RELEASE)
			{
				GYLite.GYSprite.stage.addEventListener(egret.TouchEvent.TOUCH_TAP,function(e:egret.TouchEvent):void{						
					if(GYLite.GYSprite.stageX < 50 && GYLite.GYSprite.stageY < 50)
					Log.showLog(Log.logArea && !Log.logArea.parent);
				},s);
			}
			GYLite.TimeManager.timeOut(s.doInitUI,s, 0);
			
		}
		private doInitUI():void
		{var s = this;  
			GYLite.GYSprite.player.canvas.addEventListener("webglcontextlost", function():void{				
				Log.writeLog("webgl丢失!",Log.WARN);
			}, false);
            GYLite.GYSprite.player.canvas.addEventListener("webglcontextrestored", function():void{
				Log.writeLog("webgl恢复!",Log.WARN);
			}, false);
			s.stage.addEventListener(egret.Event.RESIZE, s.resize,s);			
            LayerManager.getInstance().initLayer(s.stage);			            
			GameManager.getInstance().resize(s.stage.stageWidth,s.stage.stageHeight);			
			s.preloadModules();				
		}
		private preloadModules():void
		{
			let arr:string[] = GameManager.getInstance().preloads;
			let i:number,len:number;
			let obj:any;
			let uiCfg:UICtrlData;
			let s = this;			
			if(arr && arr.length > 0)
			{			
				len = arr.length;	
				for(i=0;i<len;++i)
				{
					obj = arr[i];
					uiCfg = UIControl.getInstance().preloadUI(obj.module, "", obj.mdVer);
					Log.writeLog(MultiLang.str59 + (i + 1) + "/" + len + "..." + obj.module + "?" + obj.mdVer, Log.IMPORTANT);
					if(uiCfg)
						s._preloadVec.push(uiCfg);
				}
				GYLite.CommonUtil.addStageLoop(s.preloadProg,s);
			}
			else
			{				
				GameManager.getInstance().gameStart();
			}				
		}
		private preloadProg(t:number):void
		{let s = this;
			let i:number,len:number;
			let percent:number = 0;
			let uiCfg:UICtrlData;
			let obj:any;
			let arr:string[] = GameManager.getInstance().preloads;			
			len = s._preloadVec.length;			
			for(i=0;i<len;++i)
			{
				uiCfg = s._preloadVec[i];
				obj = arr[i];
				if(uiCfg.loadPercent >= 1)
				{
					if(obj.open == 1)
					{
						UIControl.getInstance().openUI(uiCfg.uiPath,"",obj.mdVer,null,obj.mutual);
					}
				}
				percent += uiCfg.loadPercent;
			}
			percent = percent / len;			
			if(percent >= 1)
			{
				GYLite.CommonUtil.delStageLoop(s.preloadProg,s);
				s._preloadVec.length = 0;
				//预加载成功
				GameManager.getInstance().gameStart();
			}
		}				
        private resize(e:egret.Event):void
        {let s = this;
			if(s.stage == null)return;
			GameManager.getInstance().resize(s.stage.stageWidth,s.stage.stageHeight);
        }
        
        private spriteSheepDict:GYLite.Dictionary = new GYLite.Dictionary;
		//是否有资源
		public hasRes(key:string, aliasKey:string):boolean
		{
			let localHref:any;
			if(key == null)return null;
			localHref = (<any>window).localHref;
			if(localHref && localHref.resUrl)  
			{				
				if(aliasKey && aliasKey.indexOf("http") != 0)
					aliasKey = localHref.resUrl + aliasKey;
				else if(key.indexOf("http") != 0)
					key = localHref.resUrl + key;
			}
			return !!GYLite.GYLoader.getRes(key, aliasKey);
		}
		//是否有数据资源
		public hasDataRes(key:string):boolean
		{
			return !!GYLite.GYLoader.getDataRes(key);
		}
        public getRes(key:string,aliasKey:string = null):any
        {
            var res:GYLite.ResObject;   
			let localHref:any;
			if(key == null)return null;
			localHref = (<any>window).localHref;
			if(localHref && localHref.resUrl)  
			{				
				if(aliasKey && aliasKey.indexOf("http") != 0)
					aliasKey = localHref.resUrl + aliasKey;
				else if(key.indexOf("http") != 0)
					key = localHref.resUrl + key;
			}       
				
			if(aliasKey == "")aliasKey = null;
            res = GYLite.GYLoader.getRes(key, aliasKey);
			if(res == null)
			{
				let arr:string[] = key.split("$");
				if(arr.length > 1)				
					res = GYLite.GYLoader.getRes(arr[1], arr[0]);				
			}
            if(res == null)
            {
                Log.writeLog("资源不存在 " + key + "-" + aliasKey, Log.WARN);                
				return GameManager.getInstance().errorTexture;
            }
            return res.res;
        }
        public getDataRes(key:string):any
        {
            var res:GYLite.ResObject;  
			let localHref:any;
			if(key == null)return null;
			localHref = (<any>window).localHref;
			if(localHref && localHref.resUrl && key.indexOf("http") != 0)  
			{
				key = localHref.resUrl + key;
			}           
            res = GYLite.GYLoader.getDataRes(key);
            if(!res)
            {
                Log.writeLog("数据资源不存在 " + key, Log.WARN);                
                return null;
            }
            return res.res;
        }
        /**销毁资源
         * @param 销毁关于key指定的路径资源
        */
        public disposeRes(key:string):void
        {
			FairyGUIProto.disposePkg();
			EgretProto.deleteResByKey(key);
            GYLite.GYLoader.deleteResByKey(key);
        }
		/**获取exml文本
		 * @param path exml路径
		*/
		public getEXML(path:string,uiID:string=null):string
		{
			let s = this;
			uiID = uiID == null?(EgretProto.curRunUIID!=null?UIControl.getUIIDPath(EgretProto.curRunUIID):UIControl.getInstance().curUIIDPath):UIControl.getUIIDPath(uiID);
			path = uiID +"/"+path;
			let str:string = s.getDataRes(path);
			if(str == null)
			{
				Log.writeLog(MultiLang.str23 + path, Log.WARN);
			}
			return str;
		}

		public dragLock(val:boolean):void
		{let s = this;
			if(s._dragLock == val)return;
			s._dragLock = val;
			if(val)
				document.addEventListener("dragstart",s.dragFunc);
			else
				document.removeEventListener("dragstart",s.dragFunc);
		}
		private dragFunc(event):void
		{
			event.preventDefault();
		}	

		public static setStorage(key:string, value:string)
		{
			if(key == null)return;
			if(egret.wxgame.wx)			
				egret.wxgame.wx.setStorageSync(key,value);			
			else
				localStorage.setItem(key,value);
		}
		public static getStorage(key:string):string
		{
			if(key == null)return "";
			if(egret.wxgame.wx)
				return egret.wxgame.wx.getStorageSync(key);			
			else
				return localStorage.getItem(key);
		}
		public static clearStorage():void
		{
			if(egret.wxgame.wx)
				egret.wxgame.wx.clearStorageSync();			
			else
				localStorage.clear();
		}
		public static removeStorage(key:string):void
		{
			if(key == null)return;
			if(egret.wxgame.wx)
				egret.wxgame.wx.removeStorageSync(key);			
			else
				localStorage.removeItem(key);
		}

}